﻿#region Copyright 2012 by Roger Knapp, Licensed under the Apache License, Version 2.0
/* Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#endregion
using System;
using System.IO;
using System.Linq;
using System.Reflection;

namespace CsProjectProjector
{
    class Program
    {
        private static int DoHelp(params string[] message)
        {
            Console.WriteLine(
                Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyTitleAttribute), false).Cast<AssemblyTitleAttribute>().First().Title
                + " " +
                Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyCopyrightAttribute), false).Cast<AssemblyCopyrightAttribute>().First().Copyright
                + @"

Usage: CsProjectProjector.exe [Directory of templates] [Solution to process]
");

            if (message != null && message.Length > 0)
            {
                Console.Error.WriteLine(String.Join(Environment.NewLine, message));
                return 1;
            }
            return 0;
        }

        static int Main(string[] args)
        {
            if (args.Length <= 1 || !Directory.Exists(args[0]) ||
                args.FirstOrDefault(s => s.TrimStart('/', '-') == "?" || s.TrimStart('/', '-') == "help") != null)
                return DoHelp();

            string[] templates = Directory.Exists(args[0])
                ? Directory.GetFiles(args[0], "*.csproj")
                : Directory.GetFiles(Path.GetDirectoryName(args[0]), Path.GetFileName(args[0]));

            if (templates.Length == 0)
                return DoHelp("Unable to locate any projects in " + args[0]);

            if (args.Skip(1).Count(s => !File.Exists(s)) > 0)
                return DoHelp("One or more solutions specified could not be found.");

            foreach (string slnpath in args.Skip(1).Select(s => Path.GetFullPath(s)))
            {
                if (StringComparer.OrdinalIgnoreCase.Equals(Path.GetExtension(slnpath), ".sln"))
                {
                    new SolutionConverter(slnpath)
                        .ConvertSolution(templates);
                }
                else
                {
                    ProjectConverter
                        .ConvertProject(slnpath, templates);
                }
            }
            return 0;
        }
    }
}
